package com.reflect;

import java.lang.reflect.Method;

public class PerformanceTest {
    public void testMethod() {
        // 空方法用于测试
        int i = 1 + 1;
    }
    
    public static void main(String[] args) throws Exception {
        final int iterations = 10000000; // 一千万次调用
        PerformanceTest obj = new PerformanceTest();
        Method method = PerformanceTest.class.getMethod("testMethod");
        
        // 预热JVM
        for (int i = 0; i < 10000; i++) {
            obj.testMethod();
            method.invoke(obj);
        }
        
        // 测试直接调用
        long start = System.currentTimeMillis();
        for (int i = 0; i < iterations; i++) {
            obj.testMethod();
        }
        long directTime = System.currentTimeMillis() - start;
        
        // 测试反射调用
        start = System.currentTimeMillis();
        for (int i = 0; i < iterations; i++) {
            method.invoke(obj);
        }
        long reflectTime = System.currentTimeMillis() - start;
        
        System.out.println("直接调用耗时: " + directTime + " ms");
        System.out.println("反射调用耗时: " + reflectTime + " ms");
        System.out.println("反射比直接调用慢: " + (reflectTime / (double)directTime) + " 倍");
    }
}